import axios from 'axios'
import store from '@/store'
// import router from '../router/index'
//创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
})

service.interceptors.request.use(
  config => {
    //如果token为空，则在headers中添加token，否则直接返回
    if (store.state.token) {
      config.headers['token'] = window.sessionStorage.getItem("token")
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
//response响应拦截
axios.interceptors.response.use(response => {
    let res = response.data;
    console.log(res)
  //alert(res)
    //如果返回状态码为200，则不拦截
    if (res.code === 200) {
      return response
    } else if (res.code === 405){  //如果状态码为405，则未登录，跳转到登录界面
      //alert(res.msg); //提示错误信息
      // router.push("/UserLogin");
      //否则拒绝他，给他的信息是后台携带回来的信息
      return Promise.reject(response.data.msg)
    }else {
      return Promise.reject(response.data.msg)
    }
  },
  error => {
    console.log(error)
    if (error.response.data) {
      error.message = error.response.data.msg
    }

    if (error.response.status === 401) {
      router.push("/login")
    }
    return Promise.reject(error)
  }
)

export default service
